package com.lagou.rpcproviderspringboot.framework;

import com.lagou.protocol.RpcRequest;
import com.lagou.protocol.RpcResponse;
import com.lagou.protocol.decoder.RpcDecoder;
import com.lagou.protocol.encoder.RpcEncoder;
import com.lagou.protocol.serializer.impl.JSONSerializer;
import com.lagou.rpcproviderspringboot.framework.annotation.RpcService;
import com.lagou.rpcproviderspringboot.framework.handler.UserServiceHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * RPC服务提供者
 */
@Component
public class RpcProvider implements BeanPostProcessor {
    /**
     * 服务映射表
     */
    private Map<String, Object> serviceMap = new ConcurrentHashMap<>();

    /**
     * 记录RPC服务对应的Bean
     *
     * @param bean 要处理的bean
     * @param beanName bean的名字
     * @return 处理后的bean
     * @throws BeansException
     */
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> clz = bean.getClass();
        if (!clz.isAnnotationPresent(RpcService.class)) {
            return bean;
        }

        Class<?>[] interfaces = clz.getInterfaces();
        serviceMap.put(interfaces[0].getName(), bean);
        return bean;
    }

    /**
     * 启动RPC服务
     */
    @PostConstruct
    public void init() throws InterruptedException {
        //1.创建两个线程池对象
        NioEventLoopGroup  bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        //2.创建服务端的启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        //3.配置启动引导对象
        serverBootstrap.group(bossGroup,workGroup)
                //设置通道为NIO
                .channel(NioServerSocketChannel.class)
                //创建监听channel
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        //获取管道对象
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        //给管道对象pipeLine 设置编码
                        pipeline.addLast(new RpcEncoder(RpcResponse.class, new JSONSerializer()));
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        //把我们自顶一个ChannelHander添加到通道中
                        pipeline.addLast(new UserServiceHandler(serviceMap, new JSONSerializer()));
                    }
                });

        //4.绑定端口
        serverBootstrap.bind(8999).sync();
    }
}
